<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="queryParams"  :inline="true">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>   
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>   
        </el-form-item>
      </el-form>
    </div>

    <el-table  v-loading="loading" :data="roleList"  fit  highlight-current-row style="width: 100%;">
      <el-table-column prop="name" align="center" label="名称"  />
      <el-table-column prop="enname" align="center" label="英文名称"  />
      <el-table-column prop="roleType" :formatter="roleTypeDictFormat" align="center" label="角色类型"  />
      <el-table-column prop="dataScope" align="center" :formatter="dataScopeFormat" label="数据权限"  />
      <el-table-column label="更新时间" align="center" prop="updateDate">
        <template slot-scope="scope">
          <span>{{ scope.row.updateDate | dateFormat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination  :total="total" :page.sync="queryParams.current"  :limit.sync="queryParams.size" @pagination="getList"  />
  
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="英文名称" prop="enname">
          <el-input v-model="form.enname" placeholder="请输入英文名称" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
           <el-select v-model="form.roleType" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in roleTypeDict"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
     
        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="form.dataScope" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in dataScopeDict"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      
        <el-form-item label="菜单权限">
          <el-tree
            :data="menuList"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
import Pagination from '@/components/Pagination'
import { handleTree } from '@/utils'
import { getMenuList } from '@/api/admin/sysMenu'
import { getRoleAll, getRoleList, getRole , updateRole, saveRole, delRole} from '@/api/admin/sysRole'

export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      // 弹出层标题
      title: '',
      // 遮罩层
      loading: true,
      // 菜单表格树数据
      roleList: [],
      menuList: [],
      // 总数量
      total: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
      },
       defaultProps: {
        children: "children",
        label: "name"
      },
      
      // 表单参数
      form: {
      
      },
      // 显示状态数据字典
      roleTypeDict: [{
        value: 0,
        name: '部门经理'
      },
      {
        value: 1,
        name: '个人'
      }],
      dataScopeDict: [{
        value: 1,
        name: '所有数据'
      },
      {
        value: 2,
        name: '所在部门及以下数据'
      }, {
        value: 3,
        name: '所在部门数据'
      }, {
        value: 4,
        name: '仅本人数据'
      }],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        enname: [
          { required: true, message: '英文名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
      // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      console.log(checkedKeys)
      let menuList = []
      checkedKeys.forEach(menuId => menuList.push({id : menuId}))
      console.log(menuList)
      return menuList;
    },
     getMenuList() {
        this.menuList = [] 
        getMenuList({})
        .then((res) => {
          const { data } = res
          this.menuList = handleTree(data)
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
   // 字典翻译
    dataScopeFormat(row, column) {
      let obj = this.dataScopeDict.find(dict => dict.value == row.dataScope)
      return obj.name
    },
    roleTypeDictFormat(row, column) {
      let obj = this.roleTypeDict.find(dict => dict.value == row.roleType)
      return obj.name
    },
    /** 查询角色列表 */
    getList() {
      getRoleList(this.queryParams)
        .then((res) => {
          const { data } = res
          this.roleList = data.records
          this.total = data.total
          this.loading = false
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        enname: undefined,
        roleType: 0,
        dataScope: 4
      }
      this.$nextTick(()=>{
         this.$refs['form'].clearValidate();
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.open = true
      this.reset()
      this.getMenuList()
      this.title = '添加角色'
      this.$nextTick(() => {
        this.$refs.menu.setCheckedKeys([])
      });
    },
    /** 删除按钮操作 */
    delRole(id) {
      delRole(id).then(() => {
        this.getList()
        this.msg('删除成功')
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {   
      this.getMenuList()
      getRole(row.id)
        .then((res) => {
          this.open = true
          const { data } = res
          this.reset()
          this.form = data
          var checkedKeys = []
          data.menuList.forEach(menu =>  checkedKeys.push(menu.id))
          this.$nextTick(() => {
              this.$refs.menu.setCheckedKeys(checkedKeys)
          });
          this.title = '修改角色'
        })
        .catch((err) => {
          console.log('失败' + err)
        })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.menuList = this.getMenuAllCheckedKeys()
          if (this.form.id !== undefined) {
            updateRole(this.form).then(res => {
              this.msg('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            saveRole(this.form).then(res => {
              this.msg('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delRole(row.id)
      })
    }
  }
}
</script>
